from pydub import AudioSegment
import os

source_folder = '/Users/bruce.dai/SourceCode/MyProjects/english-learn/wavs_generator/generated_wav/Roger'
target_folder = '/Users/bruce.dai/SourceCode/MyProjects/english-learn/wav2spell/static/generated_wav/Roger'

if not os.path.exists(target_folder):
    os.makedirs(target_folder)

for filename in os.listdir(source_folder):
    if filename.endswith('.wav'):
        # Load the file
        audio_path = os.path.join(source_folder, filename)
        audio = AudioSegment.from_wav(audio_path)
        
        striped_len = len(audio.strip_silence())
        # Find the silence duration at the tail
        silence_duration = len(audio) - striped_len
        
        # Check if the silence duration is longer than 0.6 seconds
        threshold = 1000
        if silence_duration > threshold:
            # Trim the tail silence to its original 1/2
            target_length = max(len(audio) - (1/2) * silence_duration, striped_len + threshold)
            # target_length = len(audio) - (1/2) * silence_duration
            trimmed_audio = audio[:int(target_length)]
        else:
            trimmed_audio = audio

        # Save the result
        trimmed_audio_path = os.path.join(target_folder, filename)
        trimmed_audio.export(trimmed_audio_path, format='wav')
        
        print(f"Processed {filename}")
        
print("All files processed successfully!")
